package com.mengxiangnongfu.config.shiro;

import com.mengxiangnongfu.config.vo.ActiveUser;
import com.mengxiangnongfu.domain.User;
import com.mengxiangnongfu.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;

/**
 * Realm实现认证授权
 *
 * @author Yang
 */
public class UserRealm extends AuthorizingRealm {


    @Resource
    @Lazy
    private UserService userService;

    @Override
    public String getName() {
        return super.getClass().getSimpleName();
    }

    /**
     * 授权
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //身份得到的便是认证时的对象
        ActiveUser activeUser = (ActiveUser) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        return authorizationInfo;
    }

    /**
     * 认证
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        //获取用户的登录名
        String phone = authenticationToken.getPrincipal().toString();
        //根据登录名判断用户是否存在
        User user = userService.queryUserByPhone(phone);
        //用户存在
        if (null != user) {
            //组装存储在redis里面的对象
            ActiveUser activeUser = new ActiveUser();
            activeUser.setUser(user);
            //匹配密码
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(activeUser, user.getPassword(), ByteSource.Util.bytes(user.getSalt()), this.getName());
            return info;
        } else {
            return null;
        }

    }
}
